﻿using SuperMap.Data.Conversion;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace SuperMap.HB.ThemeWork
{
    class ImportDataManager
    {
        private MessageTipForm m_TipForm;
        private BackgroundWorker backgroundWorker;

        public delegate void ImportFinished(object sender, EventArgs e);
        public event ImportFinished OnImportFinished;

        public ImportDataManager()
        {
            try
            {
                backgroundWorker = new BackgroundWorker
                {
                    WorkerReportsProgress = true
                };
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        public void Import(string datasourceName, string datasetName, string filepath)
        {
            try
            {
                DataImport dataImport = new DataImport();
                ImportSettingSHP settingSHP = new ImportSettingSHP
                {
                    ImportMode = ImportMode.None,
                    IsImportAs3D = false,
                    IsImportEmptyDataset = false,
                    SourceFileCharset = Data.Charset.GB18030,
                    TargetEncodeType = Data.EncodeType.None,
                    SourceFilePath = filepath,
                    TargetDatasource = Desktop.Application.ActiveApplication.Workspace.Datasources[datasourceName],
                    TargetDatasetName = datasetName
                };
                dataImport.ImportSettings.Add(settingSHP);
                dataImport.Stepped += DataImport_Stepped;
                if (m_TipForm == null)
                {
                    m_TipForm = new MessageTipForm(backgroundWorker);
                }
                m_TipForm.Show();
                ImportResult result = dataImport.Run();
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }

        private void DataImport_Stepped(object sender, ImportSteppedEventArgs e)
        {
            try
            {
                backgroundWorker.ReportProgress(e.TotalPercent, e.Message);
                if (e.TotalPercent == 100)
                {
                    OnImportFinished?.Invoke(null, null);
                    m_TipForm.Close();
                }
            }
            catch (Exception ex)
            {
                Log.OutputBox(ex);
            }
        }
    }
}
